﻿/**
 * 接收图像对象（可以是JPG或PNG）并返回一个新的图像压缩
 * @param {Image}图像源的图像对象
 * @param {Integer} 质量输出图像质量目标
 * @return {Image} result_image_obj 图像压缩图像对象
 */
function compressFile(_fileinput_id, _preview_id, _maxWidthOrHeight) {
    $('#' + _fileinput_id).on('change', function () {
        var fileinput = this;
        var $preview = $("#" + _preview_id);
        var file = fileinput.files[0];
       
        _maxWidthOrHeight = _maxWidthOrHeight || 800;
        //_minSize = _minSize || [64, 64];
        //_maxSize = _maxSize || [800, 800];
        // check for image type (jpg and png are allowed)
        var rFilter = /^(image\/jpeg|image\/png|image\/jpg)$/i;
        if (!rFilter.test(file.type)) {
            alert('请选择jpg、jpeg或png格式的图片');
            return;
        }

        $preview.width("auto");
        $preview.attr("src", "/themes/wStyle1/Images/comm/loading.gif");
        $(".caradd").show();

        window.URL = window.URL || window.webkitURL;
        var url = window.URL.createObjectURL(file);

        var $img = new Image();
        $img.onload = function () {
            var width = $img.width,
                           height = $img.height,
                           scale = width / height;
            if (height > _maxWidthOrHeight || width > _maxWidthOrHeight) {
                if (width > height) {
                    width = parseInt(_maxWidthOrHeight);
                    height = parseInt(width / scale);
                } else {
                    height = parseInt(_maxWidthOrHeight);
                    width = parseInt(height * scale);
                }
            }
            var $canvas = $('<canvas width="' + width + '" height="' + height + '"></canvas>');
            var ctx = $canvas[0].getContext('2d');
            ctx.drawImage($img, 0, 0, width, height);
            var base64 = $canvas[0].toDataURL(file.type, 0.5);
            $preview[0].src = base64;
        }
        $img.src = url;
        $preview.attr("for", "1");
    });
}
